{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<center>\n",
    "<img src=\"../../img/ods_stickers.jpg\" />\n",
    "    \n",
    "## [mlcourse.ai](https://mlcourse.ai) – Open Machine Learning Course \n",
    "### <center> Author: Archit Rungta\n",
    "    \n",
    "## <center> Tutorial\n",
    "## <center> Imputing missing data with fancyimpute"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Hi folks!\n",
    "\n",
    "Often in real world applications of data analysis, we run into the problem of missing data. This can happen due to a multitude of reasons such as:\n",
    " - The data was compiled from different sources/times \n",
    " - Corrupted during storage\n",
    " - Certain fields were optional\n",
    " - etc.\n",
    " "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This notebook has the following sections:\n",
    " 1. Introduction\n",
    " 2. The Problem\n",
    " 3. KNN Imputation\n",
    " 4. Comparison And Application\n",
    " 5. Summary\n",
    " 6. Further Reading"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this tutorial, we look at the problem of missing data in data analytics. Then, we categorize the different types of missing data and briefly discuss the specific issue presented by each specific type. Finally, we look at various methods of handling data imputation and compare their accuracy on a real-world dataset with logistic regression. We also look at the validity of a commonly held assumption about imputation techniques. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## <center> Introduction\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Broadly, missing data is classified into 3 categories. \n",
    " - Missing Completely At Random (MCAR)\n",
    " > Values in a data set are missing completely at random (MCAR) if the events that lead to any particular data-item being missing are independent both of observable variables and of unobservable parameters of interest, and occur entirely at random\n",
    " - Missing At Random (MAR)\n",
    " >Missing at random (MAR) occurs when the missingness is not random, but where missingness can be fully accounted for by variables where there is complete information\n",
    " - Missing Not At Random (MNAR)\n",
    " >Missing not at random (MNAR) (also known as nonignorable nonresponse) is data that is neither MAR nor MCAR\n",
    " \n",
    "Data compilation from different sources is an example of MAR while data corruption is an example of MCAR. MNAR is not a problem we can fix with imputation because this is **non-ignorable non-response.** The only thing we can do about MNAR is to gather more information from different sources or ignore it all-together. As such we are not going to talk about MNAR anymore in this tutorial. \n",
    "\n",
    "All of the techniques that follow are applicable only for MCAR. However, in real world scenarios, MAR is more common. As such, we will treat MAR as MCAR only which gives a reasonably good approximation in practice."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## <center> The Problem\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's start with a toy example, \n",
    "\n",
    "\\begin{align}\n",
    "\\ y & = \\sin(x) x\\, \\text{for $|x|<=6$}\n",
    "\\end{align}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt  # plots\n",
    "import numpy as np  # vectors and matrices\n",
    "import pandas as pd  # tables and data manipulations\n",
    "import seaborn as sns  # more plots\n",
    "\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = np.linspace(-6, 6)\n",
    "y = np.asarray([x1 * np.sin(x1) for x1 in x])\n",
    "plt.scatter(x, y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's delete some points on random to get an MCAR dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "missing_fraction = 0.3\n",
    "indices = np.random.randint(1, len(x) - 1, size=int((1 - missing_fraction) * len(x)))\n",
    "x_mcar = x[indices]\n",
    "y_mcar = y[indices]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.scatter(x_mcar, y_mcar)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Throughout this tutorial, we will use MSE as an indicator of how good an imputation technique is when we have the original dataset and accuracy on predictions when we don't"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import mean_squared_error as mse"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's try the easiest methods first:\n",
    " - Mean\n",
    " - Median"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred_mean = np.array(y)\n",
    "for ind in list(set(np.linspace(0, len(x) - 1)) - set(indices)):\n",
    "    y_pred_mean[int(ind)] = np.mean(y_mcar)\n",
    "plt.scatter(x, y_pred_mean)\n",
    "mse(y_pred_mean, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred_median = np.array(y)\n",
    "for ind in list(set(np.linspace(0, len(x) - 1)) - set(indices)):\n",
    "    y_pred_median[int(ind)] = np.median(y_mcar)\n",
    "plt.scatter(x, y_pred_median)\n",
    "mse(y_pred_median, y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Well, this seems like pretty awful. Let's see what fancyimpute has to offer. \n",
    "**Note: You need TensorFlow**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install fancyimpute"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import fancyimpute"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred_knn = np.concatenate(\n",
    "    (np.array(y).reshape(-1, 1), np.array(x).reshape(-1, 1)), axis=1\n",
    ")\n",
    "for ind in indices:\n",
    "    y_pred_knn[int(ind)] = [float(\"NaN\"), y_pred_knn[int(ind)][1]]\n",
    "y_pred_knn = fancyimpute.KNN(k=3).fit_transform(y_pred_knn)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred_knn_2 = [x[0] for x in y_pred_knn]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.scatter(x, y_pred_knn_2)\n",
    "mse(y_pred_knn_2, y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As we can see, fancyimpute has performed much better than mean or median methods on this toy dataset. \n",
    "\n",
    "Next up, we get some in-depth understanding of how the KNN algorithm for fancyimpute works and apply it to some real datasets. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## <center> KNN Imputation\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ">In pattern recognition, the k-nearest neighbors algorithm is a non-parametric method used for classification and regression"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The assumption behind using KNN for missing values is that a point value can be approximated by the values of the points that are closest to it, based on other variables.\n",
    "\n",
    "The fancyimpute KNN algorithm works by calculating the k nearest neighbors which have the missing features available and then weights them based on Euclidean distance from the target row. The missing value is then calculated as a weighted mean from these neighboring rows.\n",
    "\n",
    "Below is an implementation for k = 2. Because we know our data is sorted we can code this much more efficiently. However, this isn't a general implementation. We also ignore the possibility that both of the closest neighbors can be on the same side to reduce the complexity of the code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "y_cust = np.array(y)\n",
    "for ind in indices:\n",
    "    low1 = ind - 1\n",
    "    while low1 in indices:\n",
    "        low1 = low1 - 1\n",
    "    high1 = ind + 1\n",
    "    while high1 in indices:\n",
    "        high1 = high1 + 1\n",
    "    d1 = 1 / (ind - low1)\n",
    "    d2 = 1 / (high1 - ind)\n",
    "    y_cust[ind] = (d1 * y_cust[low1] + d2 * y_cust[high1]) / (d1 + d2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.scatter(x, y_cust)\n",
    "mse(y_cust, y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## <center> Comparison and Application\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will use the Pima Indians Diabetes database for our example use case. This is an example of a MAR dataset but we will treat it as MCAR to make the best out of what we have. You can download the data from - https://www.kaggle.com/kumargh/pimaindiansdiabetescsv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"pima-indians-diabetes.csv\", header=None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " 0. Number of times pregnant\n",
    " 1. Plasma glucose concentration a 2 hours in an oral glucose tolerance test\n",
    " 2. Diastolic blood pressure (mm Hg)\n",
    " 3. Triceps skin fold thickness (mm)\n",
    " 4. 2-Hour serum insulin (mu U/ml)\n",
    " 5. Body mass index (weight in kg/(height in m)^2)\n",
    " 6. Diabetes pedigree function\n",
    " 7. Age (years)\n",
    " 8. Class variable (0 or 1)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Clearly, a person cannot have triceps sking fold thickness as 0 mm. This is a missing value and we need to replace 0 with NaN to let our algorithms know that it's a missing value.\n",
    "\n",
    "By reading the descriptions we can be sure that columns 1,2,3,4,5,6 and 7 cannot have zero values. As such, we will mark 0s as missing. \n",
    "\n",
    "Also, imputing functions work better with scaled features so we will use MinMaxScaler to scale every feature between 0 to 1."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "(df[[1, 2, 3, 4, 5, 6, 7]] == 0).sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import MinMaxScaler\n",
    "\n",
    "df = pd.DataFrame(\n",
    "    data=MinMaxScaler().fit_transform(df.values), columns=df.columns, index=df.index\n",
    ")\n",
    "df[[1, 2, 3, 4, 5, 6, 7]] = df[[1, 2, 3, 4, 5, 6, 7]].replace(0, float(\"NaN\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "fancyimpute offers many different forms of imputation methods, however, we are only comparing the four mentioned below. You can read about all of these at https://pypi.org/project/fancyimpute/"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we will compare Logistic Regression using four different imputation methods:\n",
    " - KNN\n",
    " - Mean\n",
    " - IterativeImputer\n",
    " - SoftImpute"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will first construct the dataframe for the bottom three because for KNN we need to find the optimum value of the hyperparameter. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_mean = pd.DataFrame(\n",
    "    data=fancyimpute.SimpleFill().fit_transform(df.values),\n",
    "    columns=df.columns,\n",
    "    index=df.index,\n",
    ")\n",
    "df_iterative = pd.DataFrame(\n",
    "    data=fancyimpute.IterativeImputer().fit_transform(df.values),\n",
    "    columns=df.columns,\n",
    "    index=df.index,\n",
    ")\n",
    "df_soft = pd.DataFrame(\n",
    "    data=fancyimpute.SoftImpute().fit_transform(df.values),\n",
    "    columns=df.columns,\n",
    "    index=df.index,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LogisticRegression\n",
    "\n",
    "logisticRegr = LogisticRegression()\n",
    "validation_split = 0.8\n",
    "input_columns = [0, 1, 2, 3, 4, 5, 6, 7]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "logisticRegr.fit(\n",
    "    df_mean[: int(len(df) * validation_split)][input_columns],\n",
    "    df[: int(len(df) * validation_split)][8].values,\n",
    ")\n",
    "mean_score = logisticRegr.score(\n",
    "    df_mean[int(len(df) * validation_split) :][input_columns],\n",
    "    df[int(len(df) * validation_split) :][8].values,\n",
    ")\n",
    "mean_score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "logisticRegr = LogisticRegression()\n",
    "\n",
    "logisticRegr.fit(\n",
    "    df_iterative[: int(len(df) * validation_split)][input_columns],\n",
    "    df[: int(len(df) * validation_split)][8].values,\n",
    ")\n",
    "iter_score = logisticRegr.score(\n",
    "    df_iterative[int(len(df) * validation_split) :][input_columns],\n",
    "    df[int(len(df) * validation_split) :][8].values,\n",
    ")\n",
    "iter_score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "logisticRegr = LogisticRegression()\n",
    "\n",
    "logisticRegr.fit(\n",
    "    df_soft[: int(len(df) * validation_split)][input_columns],\n",
    "    df[: int(len(df) * validation_split)][8].values,\n",
    ")\n",
    "soft_score = logisticRegr.score(\n",
    "    df_soft[int(len(df) * validation_split) :][input_columns],\n",
    "    df[int(len(df) * validation_split) :][8].values,\n",
    ")\n",
    "soft_score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "results_knn = []\n",
    "\n",
    "for k in range(2, 30):\n",
    "    df_knn = pd.DataFrame(\n",
    "        data=fancyimpute.KNN(k=k).fit_transform(df.values),\n",
    "        columns=df.columns,\n",
    "        index=df.index,\n",
    "    )\n",
    "    logisticRegr.fit(\n",
    "        df_knn[: int(len(df) * validation_split)][input_columns],\n",
    "        df[: int(len(df) * validation_split)][8].values,\n",
    "    )\n",
    "    results_knn.append(\n",
    "        logisticRegr.score(\n",
    "            df_knn[int(len(df) * validation_split) :][input_columns],\n",
    "            df[int(len(df) * validation_split) :][8].values,\n",
    "        )\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(results_knn)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Summarising the results:\n",
    " - Mean Imputation - 75.97%\n",
    " - Iterative Imputer - 77.27%\n",
    " - Soft Imputer - 77.27%\n",
    " - KNN Imputation - 80.52%"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is often claimed that mean imputation is just as good as the fancier methods such as KNN when used in conjunction with more complicated models. To test it, we build a simple neural network and train it with mean imputed data and compare results with KNN imputed data. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install keras"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.layers import Dense, Dropout\n",
    "from keras.models import Sequential\n",
    "\n",
    "model = Sequential()\n",
    "model.add(Dense(10, activation=\"relu\", input_dim=8))\n",
    "\n",
    "model.add(Dense(10, activation=\"relu\"))\n",
    "\n",
    "model.add(Dense(1, activation=\"sigmoid\"))\n",
    "\n",
    "model.compile(loss=\"binary_crossentropy\", optimizer=\"rmsprop\", metrics=[\"accuracy\"])\n",
    "model.fit(\n",
    "    df_mean[input_columns], df[8], batch_size=32, epochs=400, validation_split=0.2\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_knn = pd.DataFrame(\n",
    "    data=fancyimpute.KNN(k=8).fit_transform(df.values),\n",
    "    columns=df.columns,\n",
    "    index=df.index,\n",
    ")\n",
    "model = Sequential()\n",
    "model.add(Dense(10, activation=\"relu\", input_dim=8))\n",
    "\n",
    "model.add(Dense(10, activation=\"relu\"))\n",
    "\n",
    "model.add(Dense(1, activation=\"sigmoid\"))\n",
    "\n",
    "model.compile(loss=\"binary_crossentropy\", optimizer=\"rmsprop\", metrics=[\"accuracy\"])\n",
    "model.fit(df_knn[input_columns], df[8], batch_size=32, epochs=400, validation_split=0.2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As evident from this highly unscientific test, the common wisdom that mean imputation is just as good is not necessarily true. Even with this overkill of a model, KNN imputed data performs significantly better than mean imputed data(0.8701 - epoch 396 vs 0.7987 - epoch 324 in this run)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## <center> Summary\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Missing data is broadly classified into three categories: MCAR, MAR and MNAR. We show the abysmal performance of mean imputation and median imputation with a toy example. Next, we create an intuitive understanding of KNN imputation and write sample code for its implementation. \n",
    "\n",
    "Finally, we apply the techniques to Pima Indian Diabetes set and use four different imputation strategies. We show the superiority of KNN imputation technique over other imputation strategies for both logistic regression and neural networks, discrediting a common belief about imputation techniques."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## <center> Further Reading\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " - https://pypi.org/project/fancyimpute/\n",
    " - https://github.com/iskandr/fancyimpute/tree/master/fancyimpute\n",
    " - https://github.com/iskandr/knnimpute/blob/master/knnimpute/few_observed_entries.py\n",
    " - https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4959387/"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
